<template>
  <div>
    <el-breadcrumb separator="/" style="margin-bottom: 20px;">
      <el-breadcrumb-item :to="{ path: '/' }">点餐数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>数据统计</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="出餐统计图" name="first">
          <el-card class="box-card" shadow="always">
          <div id="main" style="width:800px;height:600px;"></div>
          </el-card>
          </el-tab-pane>
          <el-tab-pane label="每月消费统计" name="second">
          <el-card class="box-card" shadow="always">
            <div id="maintwo" style="width:800px ;height:600px;"></div>
          </el-card>
          </el-tab-pane>

          <el-tab-pane label="用户增长统计图" name="third">
          <el-card class="box-card" shadow="always">
          <div id="mainthree" style="width:800px;height:600px;"></div>
          </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>
    
  </div>
</template>

<script>
import { mapState } from "vuex";
// 引入echarts
import * as echarts from 'echarts/core';

import {
  DatasetComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
   ToolboxComponent,
  LegendComponent,
  TransformComponent
} from 'echarts/components';
import { LineChart, PieChart } from 'echarts/charts';
import { UniversalTransition, LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
  DatasetComponent,
  TitleComponent,
  TooltipComponent,
  ToolboxComponent,
  GridComponent,
  LegendComponent,
  TransformComponent,
  LineChart,
  PieChart,
  CanvasRenderer,
  UniversalTransition,
  LabelLayout
]);

export default {
  props: {},
  data() {
    return {
      dialogVisible: false,
      addForm: {},
      rules: {
        models: [
          { required: true, message: "请选择车辆类型", trigger: "change" }
        ],
        cash: [{ required: true, message: "请输入投资金额", trigger: "blur" }]
      },
      pieData: [
          { name: "重庆小面", value: 0 },
          { name: "黄焖鸡", value: 0 },
          { name: "水煮", value: 0 },
          { name: "南昌拌粉", value: 0 },
          { name: "宫保鸡丁", value: 0 },
          { name: "水煮肉片", value: 0 },
          { name: "酸汤肥牛", value: 0 },
          { name: "过桥米线", value: 0 },
      ],
      total: 0,
      all: 0,
      form: {},
      filtersData: [],
      activeName: "first"
    };
  },
  mounted() {
    // nextTick是微任务，他会让这个函数在整个页面全部完成后才去执行，不然会报错
    this.$nextTick(function() {
      this.getList();
    });
  },
  computed: {
    ...mapState(["CuisineModel", "userInfo"])
  },
  methods: {
    investDialog() {
      this.dialogVisible = true;
    },
    cashClick() {
      let obj = {
        name: this.userInfo.name,
        number: this.userInfo.number,
        telephone: this.userInfo.telephone,
        cash: this.addForm.cash,
        models: this.addForm.models,
        createTime: new Date().getTime()
      };
      this.$api.post("/api/invest/add", obj).then(res => {
        this.$message.success("投资成功");
        this.dialogVisible = false;
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    async getList() {
      const FoodList = await this.$api.get("/api/Food/list/all");
      this.pieData.forEach(item => {
        FoodList.data.data.forEach(items => {
          if (item.name === items.models) {
            item.value += items.count;
          }
        });
      });
      console.log(this.pieData);
      this.getPie();
    },
    handleClick(tab, event) {
      if (tab.name === "first") {
        this.getList();
        this.pieData = -[
          { name: "重庆小面", value: 0 },
          { name: "黄焖鸡", value: 0 },
          { name: "水煮", value: 0 },
          { name: "南昌拌粉", value: 0 },
          { name: "宫保鸡丁", value: 0 },
          { name: "水煮肉片", value: 0 },
          { name: "酸汤肥牛", value: 0 },
          { name: "过桥米线", value: 0 },
        ];
      } else if(tab.name === "second"){
        this.getListTwo();
        this.pieData = [
          { name: "重庆小面", value: 0 },
          { name: "黄焖鸡", value: 0 },
          { name: "水煮", value: 0 },
          { name: "南昌拌粉", value: 0 },
          { name: "宫保鸡丁", value: 0 },
          { name: "水煮肉片", value: 0 },
          { name: "酸汤肥牛", value: 0 },
          { name: "过桥米线", value: 0 },
        ];
      }else if(tab.name==="third"){
        this.getListThree();
        this.pieData = [
          { name: "重庆小面", value: 0 },
          { name: "黄焖鸡", value: 0 },
          { name: "水煮", value: 0 },
          { name: "南昌拌粉", value: 0 },
          { name: "宫保鸡丁", value: 0 },
          { name: "水煮肉片", value: 0 },
          { name: "酸汤肥牛", value: 0 },
          { name: "过桥米线", value: 0 },
        ];
      }
    },
    async getListTwo() {
      const packageList = await this.$api.get("/api/Food/list/all");
      this.pieData.forEach(item => {
        packageList.data.data.forEach(items => {
          if (item.name === items.models) {
            item.value += items.cash;
          }
        });
      });
      this.getPieTwo();
    },
      async getListThree() {
      const userList = await this.$api.get("/api/Food/list/all");
      this.pieData.forEach(item => {
        userList.data.data.forEach(items => {
          if (item.name === items.models) {
            item.value += items.cash;
          }
        });
      });
      this.getPiethree();
    },
    // 第三个统计图
    getPiethree(){
    var myChart = echarts.init(document.getElementById("mainthree"));

    var app = {};

     var option;

     function randomData() {
  now = new Date(+now + oneDay);
  value = value + Math.random() * 21 - 10;
  return {
    name: now.toString(),
    value: [
      [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
      Math.round(value)
    ]
  };
}
let data = [];
let now = new Date(1997, 9, 3);
let oneDay = 24 * 3600 * 1000;
let value = Math.random() * 1000;
for (var i = 0; i < 1000; i++) {
  data.push(randomData());
}
option = {
  title: {
    text: '用户增长图'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      params = params[0];
      var date = new Date(params.name);
      return (
        date.getDate() +
        '/' +
        (date.getMonth() + 1) +
        '/' +
        date.getFullYear() +
        ' : ' +
        params.value[1]
      );
    },
    axisPointer: {
      animation: false
    }
  },
  toolbox: {
            show : true,
            feature : {
                mark : {show: true},
                restore : {show: true},
                saveAsImage : {
                    show: true,
                    pixelRatio: 1,
                    title : '保存为图片',
                    type : 'png',
                    lang : ['点击保存']         
                }
            }
        },
  xAxis: {
    type: 'time',
    splitLine: {
      show: false
    }
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, '100%'],
    splitLine: {
      show: false
    }
  },
  series: [
    {
      name: 'Fake Data',
      type: 'line',
      showSymbol: false,
      data: data
    }
  ]
};
setInterval(function () {
  for (var i = 0; i < 5; i++) {
    data.shift();
    data.push(randomData());
  }
  myChart.setOption({
    series: [
      {
        data: data
      }
    ]
  });
}, 1000);

if (option && typeof option === 'object') {
    myChart.setOption(option);
}
    },



    // 第二个统计图
    getPieTwo() {
      // 绘制图表
      var myChart = echarts.init(document.getElementById("maintwo"));
      // 指定图表的配置项和数据
      var app={};
      var option;

      setTimeout(function () {
      option = {
       
     legend: {},
      title: {
        text: '当月消费比'
               },
    tooltip: {
      trigger: 'axis',
      showContent: false
    },
       toolbox: {
            show : true,
            feature : {
                mark : {show: true},
                restore : {show: true},
                saveAsImage : {
                    show: true,
                    pixelRatio: 1,
                    title : '保存为图片',
                    type : 'png',
                    lang : ['点击保存']         
                }
            }
        },
    dataset: {
      source: [
        ['product', '2012', '2013', '2014', '2015', '2016', '2017'],
        ['Milk Tea', 56.5, 82.1, 88.7, 70.1, 53.4, 85.1],
        ['Matcha Latte', 51.1, 51.4, 55.1, 53.3, 73.8, 68.7],
        ['Cheese Cocoa', 40.1, 62.2, 69.5, 36.4, 45.2, 32.5],
        ['Walnut Brownie', 25.2, 37.1, 41.2, 18, 33.9, 49.1]
      ]
    },
    xAxis: { type: 'category' },
    yAxis: { gridIndex: 0 },
    grid: { top: '55%' },
    series: [
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: { focus: 'series' }
      },
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: { focus: 'series' }
      },
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: { focus: 'series' }
      },
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: { focus: 'series' }
      },
      {
        type: 'pie',
        id: 'pie',
        radius: '30%',
        center: ['50%', '25%'],
        emphasis: {
          focus: 'self'
        },
        label: {
          formatter: '{b}: {@2012} ({d}%)'
        },
        encode: {
          itemName: 'product',
          value: '2012',
          tooltip: '2012'
        }
      }
    ]
  };
  myChart.on('updateAxisPointer', function (event) {
    const xAxisInfo = event.axesInfo[0];
    if (xAxisInfo) {
      const dimension = xAxisInfo.value + 1;
      myChart.setOption({
        series: {
          id: 'pie',
          label: {
            formatter: '{b}: {@[' + dimension + ']} ({d}%)'
          },
          encode: {
            value: dimension,
            tooltip: dimension
          }
        }
      });
    }
  });
  myChart.setOption(option);
});
    },

    // 第一个统计图
    getPie() {
      // 第一个折线图
      // 绘制图表
      var myChart = echarts.init(document.getElementById("main"));
      // 指定图表的配置项和数据
      var app = {};

      var option;

      option = {
    title: {
    text: '各菜品类消费图'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: 'Union Ads',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: 'Video Ads',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [150, 232, 201, 154, 190, 330, 410]
    },
    {
      name: 'Direct',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [320, 332, 301, 334, 390, 330, 320]
    },
    {
      name: 'Search Engine',
      type: 'line',
      stack: 'Total',
      label: {
        show: true,
        position: 'top'
      },
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [820, 932, 901, 934, 1290, 1330, 1320]
    }
  ]
},


      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);


    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          this.$emit("handle");
        })
        .catch(_ => {});
    },
    resetVisible() {
      this.$emit("handle");
    }
  },
  watch: {}
};
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}
.box-card{
  width:900px;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>